<template>
  <div class="login-container">
    <div class="login-container-wrapper flex-center">
      <div
        class="login-container-pc"
        :style="{
          display: pcDisplay,
        }"
      >
        <div class="login-container-content flex">
          <!-- 左侧数据可视化展示区 -->
          <div class="data-panel">
            <div class="data-panel-content flex-column">
              <div class="content-logo">
                <img src="/logo.png" />
                <span>云迹 · Cloudy</span>
              </div>
              <div class="content-stats mt-30 mb-30">
                <div
                  v-for="(item, index) of contentList"
                  :key="index"
                  class="content-stats-item mb-25"
                >
                  <p class="title">{{ item.title }}</p>
                  <p class="value">{{ formatNumber(item.value) }}</p>
                </div>
              </div>
              <div class="content-wordcloud mt-30">
                <div
                  v-for="(word, index) in hotWords"
                  :key="index"
                  :style="{
                    fontSize: `${word.size}px`,
                    color: word.color,
                    transform: `rotate(${word.rotate}deg)`,
                    top: `${word.top}%`,
                    left: `${word.left}%`,
                  }"
                  class="comment-word"
                >
                  {{ word.text }}
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧登录表单区 -->
          <div class="form-panel">
            <div class="form-panel-card flex-column">
              <h2 class="login-title flex-column-center">
                <img src="/cloud.png" />
                云迹登录
              </h2>
              <p class="login-subtitle">每天进步一点点</p>

              <a-form ref="loginFormRef" :model="form" :rules="rules">
                <a-form-item name="name">
                  <a-input
                    v-model:value="form.name"
                    placeholder="使用昵称或账号"
                  >
                    <template #prefix> <user-outlined type="user" /> </template>
                  </a-input>
                </a-form-item>

                <a-form-item
                  name="password"
                  has-feedback
                  style="margin-top: 16px"
                >
                  <a-input-password
                    v-model:value="form.password"
                    placeholder="请输入密码"
                  >
                    <template #prefix> <lock-outlined type="user" /> </template>
                  </a-input-password>
                </a-form-item>

                <div class="login-btn flex">
                  <a-button type="primary" :loading="loading" @click="login">
                    <span v-if="!loading">开始使用</span>
                    <span v-else>登录中...</span>
                    <ArrowRightOutlined />
                  </a-button>
                </div>

                <div class="remember-register flex mt-10">
                  <a-checkbox v-model:checked="checked">记住账号</a-checkbox>
                  <span class="register c-p" @click="register">注册</span>
                </div>
              </a-form>

              <div class="other-login">
                <a-divider>其他登录方式</a-divider>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div
        class="login-container-mobile"
        :style="{
          display: mobileDisplay,
        }"
      >
        <div class="login-mobile-wrapper flex-column">
          <div class="hot-words-wrapper">
            <div
              v-for="word of hotWords"
              :key="word.text"
              class="comment-word"
              :style="{
                fontSize: `${word.size}px`,
                color: word.color,
                transform: `rotate(${word.rotate}deg)`,
                top: `${word.top}%`,
                left: `${word.left}%`,
              }"
            >
              {{ word.text }}
            </div>
          </div>

          <div class="form-panel">
            <div class="form-panel-card flex-column">
              <h2 class="login-title flex-column-center">
                <img src="/cloud.png" />
                云迹 · Cloudy
              </h2>
              <p class="login-subtitle">每天进步一点点</p>

              <a-form ref="loginFormRef" :model="form" :rules="rules">
                <a-form-item name="name">
                  <a-input
                    v-model:value="form.name"
                    placeholder="使用昵称或账号"
                  >
                    <template #prefix> <user-outlined type="user" /> </template>
                  </a-input>
                </a-form-item>

                <a-form-item
                  name="password"
                  has-feedback
                  style="margin-top: 16px"
                >
                  <a-input-password
                    v-model:value="form.password"
                    placeholder="请输入密码"
                  >
                    <template #prefix> <lock-outlined type="user" /> </template>
                  </a-input-password>
                </a-form-item>

                <div class="login-btn flex">
                  <a-button type="primary" :loading="loading" @click="login">
                    <span v-if="!loading">开始使用</span>
                    <span v-else>登录中...</span>
                    <ArrowRightOutlined />
                  </a-button>
                </div>

                <div class="remember-register flex mt-10">
                  <a-checkbox v-model:checked="checked">记住账号</a-checkbox>
                  <span class="register c-p" @click="register">注册</span>
                </div>
              </a-form>
            </div>
          </div>

          <div class="panel-wrapper flex">
            <div
              v-for="(item, index) of contentList"
              :class="['content-item flex-center', { 'ml-30': index !== 0 }]"
            >
              <img :src="item.icon" />
              <span class="value ml-5">{{ item.value }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <a-modal
    v-model:open="dialogConfig.show"
    title="注册"
    :confirm-loading="dialogConfig.loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form
      ref="dialogFormRef"
      :model="dialogConfig.form"
      :rules="dialogConfig.rules"
      :label-col="{ span: 4 }"
    >
      <a-form-item label="昵称" name="name">
        <a-input
          v-model:value="dialogConfig.form.name"
          placeholder="昵称不得超过8个字符"
        />
      </a-form-item>
      <a-form-item label="账号" name="account" style="margin-top: 8px">
        <a-input
          v-model:value="dialogConfig.form.account"
          placeholder="请输入账号"
        />
      </a-form-item>
      <a-form-item
        label="密码"
        name="password"
        has-feedback
        style="margin-top: 8px"
      >
        <a-input-password
          v-model:value="dialogConfig.form.password"
          placeholder="密码不得少于6位"
        />
      </a-form-item>
      <a-form-item
        label="密码确认"
        name="repassword"
        has-feedback
        style="margin: 8px 0"
      >
        <a-input-password
          v-model:value="dialogConfig.form.repassword"
          placeholder="请确认密码"
        />
      </a-form-item>
      <a-form-item label="主色调" name="color" style="margin: 8px 0">
        <a-input type="color" v-model:value="dialogConfig.form.color" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import {
  ArrowRightOutlined,
  UserOutlined,
  LockOutlined,
} from "@ant-design/icons-vue";

import user from "../assets/images/icons/user.svg";
import daily from "../assets/images/icons/daily.svg";
import yearly from "../assets/images/icons/yearly.svg";
import { loginApi, registerApi, getSystemInfo } from "../api/login";
import {
  debounce,
  formatNumber,
  clearObject,
  createRandom16Color,
  validatePcMobile,
} from "../utils/util";
import { Decrypt, Encrypt } from "../utils/aes";
import { getLocal, removeLocal, setLocal } from "../utils/storage";

const pcDisplay = ref("block");
const mobileDisplay = ref("none");

onMounted(() => {
  let isMobile = validatePcMobile();
  if (isMobile) {
    pcDisplay.value = "none";
    mobileDisplay.value = "block";
  } else {
    pcDisplay.value = "block";
    mobileDisplay.value = "none";
  }
  if (getLocal("ss_name")) {
    form.value.name = getLocal("ss_name");
    form.value.password = Decrypt(getLocal("ss_password"));
    checked.value = true;
  }
  getSystemInfo().then((res) => {
    contentList.value.forEach((item) => {
      item.value = res.data[item.prop];
    });
  });
});

const contentList = ref([
  {
    title: "累计日计划",
    value: 0,
    icon: daily,
    prop: "dailyTotal",
  },
  {
    title: "累计年计划",
    value: 0,
    icon: yearly,
    prop: "yearlyTotal",
  },
  {
    title: "活跃用户数",
    value: 0,
    icon: user,
    prop: "userTotal",
  },
]);

const hotWords = ref([
  // 数据可视化看板
  {
    text: "云图绘卷",
    size: 24,
    color: "#4B0082",
    rotate: 0,
    top: 20,
    left: 15,
  },
  {
    text: "时光轨迹",
    size: 28,
    color: "#8A2BE2",
    rotate: 5,
    top: 30,
    left: 60,
  },
  {
    text: "知识星球",
    size: 20,
    color: "#20B2AA",
    rotate: -3,
    top: 50,
    left: 30,
  },
  {
    text: "星河之声",
    size: 22,
    color: "#9370DB",
    rotate: 2,
    top: 70,
    left: 45,
  },
  {
    text: "热点挖掘",
    size: 26,
    color: "#FF6347",
    rotate: -4,
    top: 40,
    left: 75,
  },
]);

function validateName(rule, value) {
  if (!value) {
    return Promise.reject("请输入昵称");
  } else if (value.length > 8) {
    return Promise.reject("昵称长度不得超过8位");
  } else {
    return Promise.resolve();
  }
}
function validatePass(rule, value) {
  if (!value) {
    return Promise.reject("请输入密码");
  } else if (value.length < 6) {
    return Promise.reject("密码长度不对");
  } else {
    return Promise.resolve();
  }
}
function validateRePass(rule, value) {
  if (!dialogConfig.form.password) {
    return Promise.reject("请先输入密码");
  } else {
    if (!value) {
      return Promise.reject("请确认密码");
    } else if (value !== dialogConfig.form.password) {
      return Promise.reject("两次输入的密码不一致");
    } else {
      return Promise.resolve();
    }
  }
}

const form = ref({});

const rules = {
  name: [{ required: true, message: "请输入昵称", trigger: "change" }],
  password: [{ required: true, validator: validatePass, trigger: "change" }],
};
const loginFormRef = ref(null);

const checked = ref(false);
const loading = ref(false);
const router = useRouter();
const login = debounce(loginMethod, 2000, true);
function loginMethod() {
  loginFormRef.value
    .validate()
    .then(() => {
      if (checked.value) {
        setLocal("ss_name", form.value.name);
        setLocal("ss_password", Encrypt(form.value.password));
      } else {
        removeLocal("ss_name");
        removeLocal("ss_password");
      }
      loading.value = true;
      let params = { ...form.value };
      params.password = Encrypt(params.password);
      loginApi(params).then((res) => {
        loading.value = false;
        if (res.code === 0) {
          message.success("登录成功!");
          setLocal("plan_user_id", res.data.userId);
          setLocal("plan_user_name", res.data.name);
          setLocal("system_main_color", res.data.color);
          setLocal("ss_token", res.data.token);
          router.push("/");
        } else {
          message.error(res.data.message);
        }
      });
    })
    .catch((error) => {});
}

function register() {
  clearObject(dialogConfig.form);
  dialogConfig.form.color = createRandom16Color();

  dialogConfig.show = true;
  nextTick(() => {
    dialogFormRef.value.resetFields();
  });
}
const dialogFormRef = ref(null);
const dialogConfig = reactive({
  show: false,
  loading: false,
  form: {},
  rules: {
    name: [
      {
        required: true,
        validator: validateName,
        trigger: "change",
      },
    ],
    account: [
      {
        required: true,
        message: "请输入账号",
        trigger: "change",
      },
    ],
    password: [
      {
        required: true,
        validator: validatePass,
        trigger: "change",
      },
    ],
    repassword: [
      {
        required: true,
        validator: validateRePass,
        trigger: "change",
      },
    ],
  },
});

function handleOk() {
  dialogFormRef.value
    .validate()
    .then(() => {
      dialogConfig.loading = true;
      let params = { ...dialogConfig.form };
      params.password = Encrypt(params.password);
      console.log(params);
      registerApi(params).then((res) => {
        dialogConfig.loading = false;
        console.log(res);
        if (res.code === 0) {
          message.success("注册成功啦!");
          dialogConfig.show = false;
        } else {
          message.error(res.data.message);
        }
      });
    })
    .catch((error) => console.error(error));
}
const handleCancel = () => {};
</script>

<style lang="less" scoped>
.login-container {
  width: 100%;
  height: 100vh;
  background-color: #fff;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    Arial, sans-serif;

  &-wrapper {
    width: 100%;
    height: 100%;

    .form-panel {
      width: 400px;
      background-color: #f8fafc;
      padding: 50px 40px;

      &-card {
        height: 100%;
        font-size: 14px;

        .login-title {
          font-size: 24px;
          font-weight: bold;
          letter-spacing: 1px;
          color: #303133;
          margin-bottom: 8px;

          img {
            width: 64px;
          }
        }

        .login-subtitle {
          color: #909399;
          margin-bottom: 40px;
          letter-spacing: 0.5px;
        }

        .login-btn {
          .ant-btn {
            width: 100%;
            height: 48px;
            background: linear-gradient(135deg, #e6f0ff 0%, #d1e0ff 100%);
            box-shadow: none;
            border: none;
            border-radius: 8px;
            color: #000;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s;

            &:hover {
              opacity: 0.9;
              box-shadow: 0 4px 12px rgba(58, 142, 230, 0.3);

              .anticon-arrow-right {
                transform: translateX(3px);
              }
            }
          }

          .anticon-arrow-right {
            margin-left: 8px;
            transition: transform 0.3s;
          }
        }

        .ant-form {
          flex: 1;
        }

        .remember-register {
          justify-content: space-between;

          .ant-checkbox-wrapper {
            align-items: center;
          }

          .register {
            color: #8a2be2;
          }
        }

        .other-login {
          .ant-divider {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }

    .login-container-pc {
      .login-container-content {
        width: 1000px;
        height: 600px;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);

        .data-panel {
          flex: 1;
          background: linear-gradient(135deg, #e6f0ff 0%, #d1e0ff 100%);
          padding: 40px;
          color: #000;
          position: relative;
          overflow: hidden;

          &-content {
            height: 100%;
            position: relative;
            z-index: 2;

            .content-logo {
              img {
                width: 64px;
                margin-right: 12px;
              }

              span {
                font-size: 22px;
                font-weight: 600;
              }
            }

            .content-stats {
              .title {
                color: rgba(0, 0, 0, 0.5);
                font-size: 16px;
                margin-bottom: 8px;
              }

              .value {
                color: rgba(0, 0, 0, 0.7);
                font-size: 28px;
                font-weight: bold;
              }
            }

            .content-wordcloud {
              flex: 1;
              position: relative;

              .comment-word {
                position: absolute;
                font-weight: 600;
                cursor: default;
                transition: all 0.3s;
                opacity: 0.9;

                &:hover {
                  opacity: 1;
                  transform: scale(1.1) rotate(0deg) !important;
                }
              }
            }
          }
        }
      }
    }
  }

  &-mobile {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .login-mobile-wrapper {
      width: 100%;
      height: 100%;
      padding-bottom: 32px;

      .hot-words-wrapper {
        position: relative;
        height: 15%;
        background: linear-gradient(135deg, #e6f0ff 0%, #d1e0ff 100%);

        .comment-word {
          position: absolute;
          font-weight: 600;
          opacity: 0.9;
        }
      }

      .form-panel {
        flex: 1;
        width: 100%;
        margin-top: 32px;
        padding: 0 5%;
        background-color: #fff;

        &-card {
          border-radius: 8px 8px 0 0;
          padding: 32px 16px;
          padding-top: 0;
          background-color: #f8fafc;

          .login-title {
            font-size: 16px;
            letter-spacing: 0;
          }

          .login-subtitle {
            font-size: 10px;
            margin-bottom: 16px;
          }

          .ant-btn {
            height: 24px;
            font-size: 10px;
          }
        }
      }

      .panel-wrapper {
        margin-top: 16px;
        justify-content: space-between;
        padding: 0 5%;

        .content-item {
          flex: 1;
          background: linear-gradient(135deg, #e6f0ff, #d1e0ff);
          border-radius: 8px;
          aspect-ratio: 4 / 3;

          img {
            width: 14px;
          }

          .value {
            margin-top: 1px;
          }
        }
      }
    }
  }
}
</style>
